<?php
/**
 * 
 * @author ronnie  (comdeng@gmail.com)
 * @link    http://fillphp.com/
 * @date   2014-5-1
 * @file      Response.php
 * @description 
 */
namespace fillphp\page;

const STATUS_OK = 200;

const STATUS_PERMANENTLY_MOVED = 301;
const STATUS_TEMPORARILY_MOVED = 302;
const STATUS_FORBIDDEN = 403;
const STATUS_NOT_FOUND = 404;

class Response
{
	var $code = STATUS_OK;
	var $content = '';
	
	private $headers = array();
	private $statusDescs = array(
		STATUS_NOT_FOUND 	=> 'Not Found',
		STATUS_OK			=> 'OK',
		STATUS_PERMANENTLY_MOVED	=> 'Permanently Moved',
		STATUS_PERMANENTLY_MOVED	=> 'Temporarily Moved',
	);
	private $contentTypeInited = false;
	
	function __construct($content = '', $code = STATUS_OK)
	{
		$this->content = $content;
		$this->code = $code;
	}
	
	/**
	 * 设置头信息
	 * @param string $key
	 * @param string $value
	 * @return \fillphp\page\Response
	 */
	function setHeader($key, $value = '')
	{
		$this->headers[] = $key.($value ? ': '.$value : '');
		if (strpos(strtolower($key), 'content-type') === 0) {
			$this->contentTypeInited = true;
		}
		return $this;
	}
	
	/**
	 * 
	 * @param string $url
	 * @return \fillphp\page\Response
	 */
	function redirect($url)
	{
		$this->setHeader('Location: '.$url);
		return $this;
	}
	
	
	/**
	 * 根据Request的情况做一下准备
	 * @param \fillphp\page\Request $request
	 * @return \fillphp\page\Response
	 */
	function prepare($request)
	{
		if (!$this->contentTypeInited) {
			$charset = $request->charset;
			$format = $request->format;
			
			$contentType = '';
			switch($format) {
				case FORMAT_HTML:
					$contentType = 'text/html';
					break;
				case FORMAT_JSON:
					$contentType = 'application/json';
					break;
				case FORMAT_TEXT:
					$contentType = 'text/plain';
					break;
				case FORMAT_XML:
					$contentType = 'text/xml';
					break;
				case FORMAT_JAVASCRIPT:
					$contentType = 'application/x-javascript';
					break;
				case FORMAT_XLS:
					//TODO
					break;
			}
			$this->setHeader('Content-type', $contentType.';charset='.$charset);
		}
		return $this;	
	}
	
	function send()
	{
		$this->sendHeaders();
		$this->sendContent();
	}
	
	function sendHeaders()
	{
		if (isset($this->statusDescs[$this->code])) {
			$desc = $this->statusDescs[$this->code];
			$this->setHeader(sprintf('%s/%s %d %s', 'HTTP', '1.1', $this->code, $desc));
		}
		//var_dump($this->headers);die();
		foreach($this->headers as $header) {
			header($header);
		}
	}
	
	function sendContent()
	{
		if ($this->content) {
			echo $this->content;
		}
	}
	
	function __toString()
	{
		return sprintf('%s/%s %d %s', 'HTTP', '1.1', $this->code, $this->statusDescs[$this->code]);
	}
}